<script setup lang="ts">
import { ref } from 'vue';
import { useChatStore } from '../../stores/chatStore';
import { storeToRefs } from 'pinia';
import ChatList from './ChatList.vue';
import SearchBar from '../SearchBar.vue';
import { API_CONFIG } from '../../config/apiConfig';
import { useI18n } from 'vue-i18n';

const chatStore = useChatStore();
const { t } = useI18n<{ message: typeof import('../../locales/en-US').default }>();
const { searchQuery, currentChatType } = storeToRefs(chatStore);
const { updateSearchQuery, addChat, setActiveChat, addMessage, switchChatType } = chatStore;

// 添加侧边栏展开/收缩状态
const isExpanded = ref(true);

// 定义emit
const emit = defineEmits<{
  (e: 'toggle-sidebar', expanded: boolean): void
}>();

function toggleSidebar() {
  isExpanded.value = !isExpanded.value;
  // 发出事件通知父组件
  emit('toggle-sidebar', isExpanded.value);
}

function handleSearch(query: string) {
  updateSearchQuery(query);
}

async function createNewChat(chatType: number) {
  try {
    const response = await fetch(`${API_CONFIG.BASE_URL}/chat`, {
      method: 'POST',
      credentials: 'include',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
         type:chatType
        })
    });
    
    const res = await response.json();
    if (res.code === "0") {
      // 确保 chatId 是数字类型
      const chatId = res.data;
      
      // 将新会话添加到列表
      const newChat = {
        id: chatId,  // 确保 ID 是数字类型
        name: t('chat.newSession'),
        participants: [],
        lastMessage: {  // 使用一个空的 Message 对象
          id: '',
          content: '',
          senderId: '',
          timestamp: new Date()
        }
      };
      
      // 添加到 store 中
      addChat(newChat);
      
      // 设置为当前活动会话
      setActiveChat(chatId);

      // 添加欢迎消息
      addMessage({
        id: `welcome-${Date.now()}`,
        content: t('chat.welcomeMessage'),
        senderId: 'assistant',
        timestamp: new Date()
      });
    }
  } catch (error) {
    console.error(t('chat.createSessionError'), error);
    alert(`${t('chat.createSessionError')}: ${error instanceof Error ? error.message : t('common.unknownError')}`);
  }
}
</script>

<template>
  <div class="sidebar" :class="{ 'collapsed': !isExpanded }">
    <div class="sidebar-content" v-show="isExpanded">
      <!-- 移动端关闭按钮 -->
      <button 
        class="mobile-close-button"
        @click="toggleSidebar"
        aria-label="关闭侧边栏"
      >
        <svg 
          xmlns="http://www.w3.org/2000/svg" 
          width="24" 
          height="24" 
          viewBox="0 0 24 24" 
          fill="none" 
          stroke="currentColor" 
          stroke-width="2" 
          stroke-linecap="round" 
          stroke-linejoin="round"
        >
          <line x1="18" y1="6" x2="6" y2="18"></line>
          <line x1="6" y1="6" x2="18" y2="18"></line>
        </svg>
      </button>

      <!-- AI能力选择区域 -->
      <div class="ai-capabilities">
        <div class="section-header">
          <div class="section-icon">⚛️</div>
          <h3>AI能力矩阵</h3>
        </div>
        
        <div class="capability-grid">
          <div class="capability-card" :class="{ 'active': currentChatType === 0 }" @click="switchChatType(0)">
            <div class="capability-icon">
              <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <path d="M6 9v12"></path>
                <path d="M18 9v12"></path>
                <path d="M3 6h18"></path>
                <path d="M12 3v18"></path>
                <path d="M3 15h18"></path>
              </svg>
            </div>
            <span>科研助手</span>
          </div>
          <div class="capability-card" :class="{ 'active': currentChatType === 1 }" @click="switchChatType(1)">
            <div class="capability-icon">
              <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <path d="M12 20h9"></path>
                <path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"></path>
              </svg>
            </div>
            <span>仓管助手</span>
          </div>
        </div>
      </div>

      <!-- 新建对话按钮 -->
      <button class="new-chat-btn" @click="() => createNewChat(currentChatType)">
        <span class="plus-icon">+</span>
        <span>创建AI对话</span>
      </button>

      <!-- 对话历史 -->
      <div class="chat-history">
        <div class="section-header">
          <div class="section-icon">🕒</div>
          <h3>对话历史</h3>
        </div>
        
        <div class="search-container">
          <SearchBar :value="searchQuery" @search="handleSearch" />
        </div>
        
        <ChatList />
      </div>
    </div>
    
    <!-- 当侧边栏收缩时显示的展开按钮 -->
    <button 
      v-if="!isExpanded" 
      class="expand-button" 
      @click="toggleSidebar" 
      :title="'展开侧边栏'"
    >
      <svg 
        xmlns="http://www.w3.org/2000/svg" 
        width="16" 
        height="16" 
        viewBox="0 0 24 24" 
        fill="none" 
        stroke="currentColor" 
        stroke-width="2" 
        stroke-linecap="round" 
        stroke-linejoin="round"
        class="rotate-180"
      >
        <polyline points="15 18 9 12 15 6"></polyline>
      </svg>
    </button>
    
    <!-- 移动端专用的展开按钮 -->
    <button 
      class="mobile-expand-button"
      :class="{ 'mobile-expand-button-visible': !isExpanded }"
      @click="toggleSidebar" 
      :title="'展开侧边栏'"
    >
      <svg 
        xmlns="http://www.w3.org/2000/svg" 
        width="16" 
        height="16" 
        viewBox="0 0 24 24" 
        fill="none" 
        stroke="currentColor" 
        stroke-width="2" 
        stroke-linecap="round" 
        stroke-linejoin="round"
        class="rotate-180"
      >
        <polyline points="15 18 9 12 15 6"></polyline>
      </svg>
    </button>
    
    <!-- 添加遮罩层 -->
    <!-- <div 
      class="sidebar-overlay" 
      @click="toggleSidebar"
      :class="{ 'sidebar-overlay-visible': isExpanded }"
    ></div> -->
  </div>
</template>

<style scoped>
.sidebar {
  position: relative;
  width: 320px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border-right: 1px solid rgba(255, 255, 255, 0.2);
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  transition: all 0.3s ease;
  box-shadow: none; /* 移除默认阴影 */
}

/* 仅在移动设备上使用固定定位和阴影 */
@media (max-width: 768px) {
  .sidebar {
    position: fixed;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
    z-index: 1000;
  }
}

.sidebar.collapsed {
  width: 50px;
}

.sidebar-content {
  flex: 1;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  opacity: 1;
  transition: opacity 0.3s ease;
  padding: 16px;
  scrollbar-width: thin;
  scrollbar-color: rgba(0, 0, 0, 0.2) transparent;
  height: 100%; /* 确保内容区域占满高度 */
  position: relative;
  gap: 16px;
}

/* 蜂窝背景 */
.sidebar-content::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: 
    radial-gradient(circle at 50% 50%, rgba(102, 126, 234, 0.08) 1px, transparent 2px),
    radial-gradient(circle at 25% 75%, rgba(102, 126, 234, 0.08) 1px, transparent 2px),
    radial-gradient(circle at 75% 25%, rgba(102, 126, 234, 0.08) 1px, transparent 2px);
  background-size: 60px 60px;
  z-index: -1;
  opacity: 0.8;
  animation: honeycomb-move 20s linear infinite;
}

@keyframes honeycomb-move {
  0% {
    background-position: 0 0;
  }
  100% {
    background-position: 60px 60px;
  }
}

/* AI能力选择区域 */
.ai-capabilities {
  position: relative;
  background: rgba(255, 255, 255, 0.6);
  border-radius: 16px;
  padding: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.4);
  backdrop-filter: blur(12px);
  transition: all 0.3s ease;
  margin-bottom: 16px;
  overflow: hidden;
}

.ai-capabilities::before {
  content: '';
  position: absolute;
  inset: 0;
  background: linear-gradient(
    135deg,
    rgba(0, 255, 255, 0.1) 0%,
    rgba(255, 255, 255, 0) 50%,
    rgba(128, 0, 128, 0.1) 100%
  );
  z-index: -1;
}

.ai-capabilities:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 24px rgba(0, 0, 0, 0.15);
  background: rgba(255, 255, 255, 0.8);
}

.section-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
}

.section-icon {
  font-size: 18px;
}

.section-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #2d3748;
}

.capability-grid {
  display: flex;
  gap: 12px;
}

.capability-card {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 16px;
  background: rgba(255, 255, 255, 0.9);
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  backdrop-filter: blur(5px);
  flex: 1;
}

.capability-card:hover {
  background: rgba(255, 255, 255, 1);
  border-color: rgba(102, 126, 234, 0.3);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.capability-card.active {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-color: transparent;
  color: white;
}

.capability-icon {
  font-size: 16px;
  line-height: 1;
}

.capability-card span {
  font-size: 14px;
  font-weight: 500;
  white-space: nowrap;
}

@media (max-width: 768px) {
  .capability-grid {
    flex-direction: column;
  }
  
  .capability-card {
    padding: 8px 12px;
    border-radius: 16px;
  }
}

/* 新建对话按钮 */
.new-chat-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  width: 100%;
  height: 44px;
  padding: 0 20px;
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.9) 0%, rgba(118, 75, 162, 0.9) 100%);
  color: white;
  border: none;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 
    0 4px 16px rgba(102, 126, 234, 0.3),
    0 0 0 1px rgba(255, 255, 255, 0.1) inset,
    0 0 0 2px rgba(102, 126, 234, 0.2);
  position: relative;
  overflow: hidden;
  margin-bottom: 16px;
  z-index: 1;
}

.new-chat-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.15) 0%, rgba(255, 255, 255, 0) 50%);
  opacity: 0;
  transition: opacity 0.3s ease;
  z-index: -1;
}

.new-chat-btn::after {
  content: '';
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: linear-gradient(
    to bottom right,
    rgba(255, 255, 255, 0) 45%,
    rgba(255, 255, 255, 0.1) 50%,
    rgba(255, 255, 255, 0) 55%
  );
  transform: rotate(30deg);
  transition: all 0.6s ease;
  z-index: -1;
}

.new-chat-btn:hover {
  transform: translateY(-2px);
  box-shadow: 
    0 6px 24px rgba(102, 126, 234, 0.4),
    0 0 0 1px rgba(255, 255, 255, 0.2) inset,
    0 0 0 2px rgba(102, 126, 234, 0.3);
}

.new-chat-btn:hover::before {
  opacity: 1;
}

.new-chat-btn:hover::after {
  transform: translateX(100%) rotate(30deg);
}

.new-chat-btn:active {
  transform: translateY(0);
  box-shadow: 
    0 2px 8px rgba(102, 126, 234, 0.4),
    0 0 0 1px rgba(255, 255, 255, 0.1) inset,
    0 0 0 2px rgba(102, 126, 234, 0.2);
}

.plus-icon {
  font-size: 20px;
  font-weight: bold;
  transition: all 0.3s ease;
  position: relative;
}

.new-chat-btn:hover .plus-icon {
  transform: scale(1.1);
  text-shadow: 0 0 8px rgba(255, 255, 255, 0.6);
}

/* 对话历史区域 */
.chat-history {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background: rgba(255, 255, 255, 0.98);
  border-radius: 16px;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.4);
  backdrop-filter: blur(12px);
  padding: 16px;
  transition: all 0.3s ease;
}

.chat-history:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 28px rgba(0, 0, 0, 0.15);
}

.search-container {
  margin-bottom: 16px;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 12px;
  padding: 8px 12px;
  border: 1px solid rgba(255, 255, 255, 0.4);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.2s ease;
}

.search-container:hover {
  background: rgba(255, 255, 255, 0.9);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.search-container :deep(.search-container) {
  margin: 0;
}

/* 展开/收缩按钮 */
.expand-button {
  position: absolute;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  width: 32px;
  height: 32px;
  background: rgba(255, 255, 255, 0.9);
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.expand-button:hover {
  background: white;
  transform: translateX(-50%) translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.expand-button svg.rotate-180 {
  transform: rotate(180deg);
}

/* 移动端关闭按钮 */
.mobile-close-button {
  display: none;
  position: absolute;
  top: 16px;
  right: 16px;
  width: 36px;
  height: 36px;
  background-color: rgba(255, 255, 255, 0.9);
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  cursor: pointer;
  z-index: 1001;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.2s ease;
  color: #374151;
}

.mobile-close-button:hover {
  background-color: rgba(255, 255, 255, 1);
  transform: scale(1.05);
}

/* 移动端专用按钮样式 */
.mobile-expand-button {
  position: fixed;
  top: 16px;
  left: 16px;
  z-index: 1002;
  background-color: rgba(255, 255, 255, 0.9);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border-radius: 50%;
  width: 36px;
  height: 36px;
  display: none;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  opacity: 0;
  visibility: hidden;
  transform: translateX(-100%);
  border: none;
  outline: none;
  cursor: pointer;
}

.mobile-expand-button-visible {
  opacity: 1;
  visibility: visible;
  transform: translateX(0);
}

/* 遮罩层 - 仅在移动设备上显示 */
.sidebar-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 999;
  opacity: 0;
  visibility: hidden;
  transition: opacity 0.3s ease, visibility 0.3s ease;
  pointer-events: none;
  backdrop-filter: blur(2px);
  display: none; /* 默认不显示 */
}

@media (max-width: 768px) {
  .sidebar-overlay {
    display: block; /* 仅在移动设备上显示 */
  }
  
  .sidebar-overlay-visible {
    opacity: 1;
    visibility: visible;
    pointer-events: auto;
    cursor: pointer;
  }
}

/* 自定义滚动条 */
.sidebar-content::-webkit-scrollbar {
  width: 6px;
}

.sidebar-content::-webkit-scrollbar-track {
  background: transparent;
}

.sidebar-content::-webkit-scrollbar-thumb {
  background-color: rgba(0, 0, 0, 0.2);
  border-radius: 3px;
}

.sidebar-content::-webkit-scrollbar-thumb:hover {
  background-color: rgba(0, 0, 0, 0.3);
}

@media (max-width: 768px) {
  .sidebar {
    position: fixed;
    top: 0;
    left: 0;
    width: 85%;
    max-width: 320px;
    height: 100vh;
    z-index: 1000;
    background: rgba(255, 255, 255, 0.98);
    transform: translateX(-100%);
    transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  }

  .sidebar:not(.collapsed) {
    transform: translateX(0);
  }

  /* 调整移动端蜂窝背景 */
  .sidebar-content::before {
    background-size: 40px 40px;
    opacity: 0.6;
  }

  /* 调整卡片样式 */
  .ai-capabilities,
  .chat-history {
    padding: 12px;
    border-radius: 12px;
  }

  /* 调整按钮样式 */
  .new-chat-btn {
    padding: 14px;
    font-size: 15px;
  }

  /* 调整搜索框 */
  .search-container {
    padding: 6px 10px;
  }

  /* 调整能力卡片网格 */
  .capability-grid {
    grid-template-columns: 1fr;
    gap: 8px;
  }

  .capability-card {
    padding: 12px;
  }

  .mobile-close-button {
    display: flex;
  }

  .mobile-expand-button {
    display: flex;
  }

  .expand-button {
    display: none;
  }
}
</style>